package com.abc.rule.aviator;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 当前月和字段的月进行相减+1
 */
public class MonthBetweenFunction extends AbstractFunction {

   @Override
   public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {

      try {
         Object left = FunctionUtils.getJavaObject(arg1, env);

         Date cur = new Date();

         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");

         int monBetween = getMonthNum(format.parse(left.toString()), cur) + 1;

         System.out.println(monBetween);

         return new AviatorLong(monBetween);
      }
      catch (Exception e) {
         System.out.println(e.getMessage());
         return new AviatorLong(0);
      }
   }

   @Override
   public String getName() {
      return "monBetween";
   }

   public static int getMonthNum(Date date1, Date date2) {
      Calendar cal1 = Calendar.getInstance();
      cal1.setTime(date1);
      Calendar cal2 = Calendar.getInstance();
      cal2.setTime(date2);
      return (cal2.get(1) - cal1.get(1)) * 12 + (cal2.get(2) - cal1.get(2));

   }

}